package com.offcn.oauth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 网络安全配置
 *
 * @author 秋林
 * @date 2022/10/13 12:44:06
 */
@Configuration
@EnableWebSecurity
@Order(-1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 忽略安全拦截的URL
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/user/login",
                "/user/logout",
                "/oauth/login",
                "/css/**",
                "/data/**",
                "/fonts/**",
                "/img/**",
                "/js/**",
                // 添加
                "/login",
                "/login.html",
                "/favicon.ico",
                "/plugins/**");
    }

    /**
     * 创建授权管理认证对象
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }

    /**
     * 采用BCryptPasswordEncoder对密码进行编码
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * 配置
     *
     * @param http http
     * @throws Exception 异常
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                //启用Http基本身份验证
                .httpBasic()
                .and()
                //限制基于Request请求访问
                .authorizeRequests()
                .anyRequest()
                //其他请求都需要经过验证
                .authenticated();
        //登录配置
        //自定义登录地址
        http.formLogin().loginPage("/oauth/login")
                //登录处理地址()
                .loginProcessingUrl("/user/login");

    }
}
